import {
  Canvas,
  ColorMatrix,
  Group,
  Image,
  Path,
  Skia,
  useCanvasRef,
  useImage,
} from "@shopify/react-native-skia";
import {
  forwardRef,
  useCallback,
  useEffect,
  useImperativeHandle,
  useMemo,
  useState,
} from "react";
import { StyleSheet, View } from "react-native";
import { useDerivedValue, useSharedValue } from "react-native-reanimated";
import { CropGestureHandler } from "./CropGestureHandler";
import {
  getCircleCropPath,
  getCropRectPath,
  getDragHandles,
  getGridPath,
  getHandlePath,
  updateCropRectByToolKey,
} from "./cropUtils";
import { Layer } from "./types";

 
interface DragHandle {
  x: number;
  y: number;
  type:
    | "top-left"
    | "top-right"
    | "bottom-left"
    | "bottom-right"
    | "top"
    | "bottom"
    | "left"
    | "right";
}

interface SkiaImageEditorProps {
  image: { path: string } | { image: any };
  onSave?: () => void;
  onCancel?: () => void;
  toolKey?: string;
  disabled?: boolean; // 控制触摸事件是否启用
  marginHorizontal?: number; // 图片左右边距
  filterData?: any; // 滤镜数据
}

export interface CropRect {
  x: number;
  y: number;
  width: number;
  height: number;
}

interface SkiaImageEditorRef {
  cropImage: () => any | null;
  getCropRect: () => CropRect;
  // 变换控制方法
  rotateImage: (angle: number) => void;
  rotateLeft: () => void;
  rotateRight: () => void;
  flipHorizontal: () => void;
  flipVertical: () => void;
  resetTransform: () => void;
  // 图层管理方法
  getLayers: () => Layer[];
  setLayers: (layers: Layer[]) => void;
  toggleLayerVisibility: (layerId: string) => void;
  toggleLayerLock: (layerId: string) => void;
}

/**
 * 基于React Native Skia的图片编辑器组件
 * 提供裁剪、旋转、滤镜、文字、贴纸、调整等功能
 */
const SkiaImageEditor = forwardRef<SkiaImageEditorRef, SkiaImageEditorProps>(
  ({ image, toolKey, marginHorizontal = 0, disabled = false, filterData }, ref) => {
    const canvasRef = useCanvasRef();

    const pathImage = useImage("path" in image ? image.path : "");
    const directImage = "image" in image ? image.image : null;
    const skiaImage = directImage || pathImage;

    const [containerSize, setContainerSize] = useState<{
      width: number;
      height: number;
    }>({
      width: 0,
      height: 0,
    });

    const [canvasPosition, setCanvasPosition] = useState({ x: 0, y: 0 });

    // 图层状态 - 内部管理
    const [internalLayers, setInternalLayers] = useState<Layer[]>(() => {
      const defaultLayer: Layer = {
        id: "base-image",
        name: "背景图片",
        type: "image",
        locked: true,
        visible: true,
        zIndex: 0,
        data: {
          uri: "path" in image ? image.path : "", // 使用传入的图片路径作为缩略图
          width: skiaImage?.width() || 0,
          height: skiaImage?.height() || 0,
        },
      };
      return [defaultLayer];
    });

    // 裁剪框状态 - 使用共享值
    const cropRectShared = useSharedValue<CropRect>({
      x: 0,
      y: 0,
      width: 0,
      height: 0,
    });

    // 是否正在交互 - 用于控制网格线显示
    const isInteracting = useSharedValue(false);

    // 变换状态
    const [rotationAngle, setRotationAngle] = useState(0);
    const [isFlipHorizontal, setIsFlipHorizontal] = useState(false);
    const [isFlipVertical, setIsFlipVertical] = useState(false);
    const [cumulativeRotation, setCumulativeRotation] = useState(0);
    const [cumulativeScale, setCumulativeScale] = useState(1); // 累积缩放系数
    const [currentFilter, setCurrentFilter] = useState<any>(null); // 当前滤镜

    // 从滤镜数据中获取色彩矩阵
    const getColorMatrix = useCallback((filterData: any) => {
      if (!filterData) {
        return null;
      }

      console.log("SkiaImageEditor: 应用滤镜", filterData.label, "色彩矩阵:", filterData.colorMatrix);
      
      // 直接使用FilterEditor传来的色彩矩阵
      return filterData.colorMatrix || null;
    }, []);

    // 监听滤镜数据变化
    useEffect(() => {
      if (filterData) {
        console.log("SkiaImageEditor 收到滤镜数据:", filterData);
        console.log("滤镜key:", filterData.key);
        console.log("滤镜名称:", filterData.label);
        console.log("LUT文件:", filterData.lut);
        console.log("预览图片:", filterData.previewImage);
        
        // 获取并应用色彩矩阵
        const colorMatrix = getColorMatrix(filterData);
        setCurrentFilter(colorMatrix);
        console.log("滤镜已应用:", colorMatrix ? "成功" : "失败");
      } else {
        console.log("SkiaImageEditor 滤镜数据为空");
        setCurrentFilter(null);
      }
    }, [filterData, getColorMatrix]);

    // 计算旋转后的原始尺寸（不受容器限制）
    const rotatedOriginalSize = useMemo(() => {
      if (!skiaImage) {
        return { width: 0, height: 0 };
      }

      const originalWidth = skiaImage.width();
      const originalHeight = skiaImage.height();

      // 根据旋转角度判断是否需要交换宽高
      const isRotated = Math.abs(cumulativeRotation) % 180 !== 0;

      return {
        width: isRotated ? originalHeight : originalWidth,
        height: isRotated ? originalWidth : originalHeight,
      };
    }, [skiaImage, cumulativeRotation]);

    // 计算图片显示尺寸（确保不超出画布边界）
    const imageSize = useMemo(() => {
      if (
        !skiaImage ||
        containerSize.width === 0 ||
        containerSize.height === 0
      ) {
        return { width: 0, height: 0 };
      }

      const { width: effectiveWidth, height: effectiveHeight } =
        rotatedOriginalSize;

      // 考虑左右边距后的可用尺寸
      const availableWidth = containerSize.width - marginHorizontal * 2;
      const availableHeight = containerSize.height;

      // 计算按宽度和按高度适配的比例
      const scaleByWidth = availableWidth / effectiveWidth;
      const scaleByHeight = availableHeight / effectiveHeight;

      // 选择较小的比例，确保图片完全显示在容器内
      const scale = Math.min(scaleByWidth, scaleByHeight);

      const displayWidth = effectiveWidth * scale;
      const displayHeight = effectiveHeight * scale;

      return {
        width: Math.round(displayWidth),
        height: Math.round(displayHeight),
      };
    }, [
      skiaImage,
      rotatedOriginalSize,
      containerSize.width,
      containerSize.height,
      marginHorizontal,
    ]);

    // 根据toolKey设置裁剪框
    const handleUpdateCropRect = useCallback(
      (toolKey?: string) => {
        const newCropRect = updateCropRectByToolKey(
          toolKey,
          imageSize,
          containerSize
        );
        cropRectShared.value = newCropRect;
      },
      [imageSize, containerSize, cropRectShared]
    );

    // 生成裁剪框路径 - 始终相对于原点(0,0)生成路径
    const getCropRectPathString = useDerivedValue(() => {
      const currentRect = cropRectShared.value;
      const originRect = {
        x: 0,
        y: 0,
        width: Math.round(currentRect.width * 100) / 100,
        height: Math.round(currentRect.height * 100) / 100,
      };
      if (toolKey === "circle") {
        return getCircleCropPath(originRect);
      }
      return getCropRectPath(originRect);
    });

    // 当图片尺寸或toolKey变化时更新裁剪框
    useEffect(() => {
      if (
        imageSize.width > 0 &&
        imageSize.height > 0 &&
        containerSize.width > 0 &&
        containerSize.height > 0
      ) {
        handleUpdateCropRect(toolKey);
      }
    }, [
      imageSize.width,
      imageSize.height,
      containerSize.width,
      containerSize.height,
      toolKey,
      cumulativeRotation,
      handleUpdateCropRect,
    ]);

    // 移除useAnimatedReaction，避免双向更新导致的抖动
    // 现在CropGestureHandler直接更新共享值，不需要同步到React状态

    const handleLayout = (event: any) => {
      const { width, height, x, y } = event.nativeEvent.layout;
      if (width > 0 && height > 0 && isFinite(width) && isFinite(height)) {
        setContainerSize({ width, height });
        setCanvasPosition({ x, y });
      }
    };

    // 从cropRect生成变换矩阵 - 用于共享值
    const matrix = useDerivedValue(() => {
      const m = Skia.Matrix();
      const currentRect = cropRectShared.value;
      if (currentRect.width > 0) {
        m.translate(
          Math.round(currentRect.x * 100) / 100,
          Math.round(currentRect.y * 100) / 100
        );
      }
      return m;
    });

    // 图片变换矩阵 - 用于旋转、翻转等操作
    const transformMatrix = useDerivedValue(() => {
      const m = Skia.Matrix();

      // 获取原始图片尺寸
      const { width: originalWidth, height: originalHeight } =
        rotatedOriginalSize;
      if (originalWidth === 0 || originalHeight === 0) return m;

      // 计算旋转后的边界框尺寸（外接矩形）
      const radians = (rotationAngle * Math.PI) / 180;
      const cos = Math.abs(Math.cos(radians));
      const sin = Math.abs(Math.sin(radians));

      // 旋转后图片的外接矩形尺寸（必然 ≥ 原始尺寸）
      const rotatedWidth = originalWidth * cos + originalHeight * sin;
      const rotatedHeight = originalWidth * sin + originalHeight * cos;

      const scaleX = rotatedWidth / originalWidth; // 横向放大倍数
      const scaleY = rotatedHeight / originalHeight; // 纵向放大倍数
      const fitScale = Math.max(scaleX, scaleY); // 取最大值

      const finalScale = fitScale;

      // 计算显示区域中心点（用于围绕中心旋转/缩放）
      const centerX = imageSize.width / 2;
      const centerY = imageSize.height / 2;

      // 应用变换：先平移到中心→缩放→旋转→翻转→平移回原位置
      m.translate(centerX, centerY); // 移到中心（原点暂时设为中心）
      m.scale(finalScale, finalScale); // 应用缩放（放大）
      m.rotate(radians); // 应用旋转（弧度制）

      // 应用水平/垂直翻转（通过负缩放实现）
      if (isFlipHorizontal || isFlipVertical) {
        m.scale(
          isFlipHorizontal ? -1 : 1, // 水平翻转：X轴缩放-1
          isFlipVertical ? -1 : 1 // 垂直翻转：Y轴缩放-1
        );
      }

      m.translate(-centerX, -centerY); // 移回原始位置（原点复位）

      return m;
    }, [
      imageSize.width,
      imageSize.height,
      rotationAngle,
      isFlipHorizontal,
      isFlipVertical,
      rotatedOriginalSize,
      cumulativeScale,
    ]);

    // 图层管理方法
    const updateLayers = (newLayers: Layer[]) => {
      setInternalLayers(newLayers.sort((a, b) => b.zIndex - a.zIndex));
    };

    const toggleLayerVisibility = (layerId: string) => {
      const updatedLayers = internalLayers.map((layer) =>
        layer.id === layerId ? { ...layer, visible: !layer.visible } : layer
      );
      updateLayers(updatedLayers);
    };

    const toggleLayerLock = (layerId: string) => {
      const updatedLayers = internalLayers.map((layer) =>
        layer.id === layerId ? { ...layer, locked: !layer.locked } : layer
      );
      updateLayers(updatedLayers);
    };

    const reorderLayers = (newOrder: Layer[]) => {
      const updatedLayers = newOrder.map((layer, index) => ({
        ...layer,
        zIndex: newOrder.length - index,
      }));
      updateLayers(updatedLayers);
    };

    // 变换控制方法
    const rotateImage = useCallback(
      (angle: number) => {
        setRotationAngle(angle);

        // 计算新的缩放系数，确保旋转后边缘不超出原边框
        const { width: originalWidth, height: originalHeight } =
          rotatedOriginalSize;
        if (originalWidth > 0 && originalHeight > 0) {
          const radians = (angle * Math.PI) / 180;
          const cos = Math.abs(Math.cos(radians));
          const sin = Math.abs(Math.sin(radians));

          // 计算旋转后的边界框尺寸
          const rotatedWidth = originalWidth * cos + originalHeight * sin;
          const rotatedHeight = originalWidth * sin + originalHeight * cos;

          // 修正：用旋转后的尺寸 / 原始尺寸，得到放大比例
          const scaleX = rotatedWidth / originalWidth;
          const scaleY = rotatedHeight / originalHeight;
          const fitScale = Math.min(scaleX, scaleY); // 取最小值，确保图片完全填充且不超出

          // 更新累积缩放系数
          setCumulativeScale((prevScale) => Math.max(prevScale, fitScale));
        }

        console.log("旋转图片 - 角度:", angle, "累积缩放:", cumulativeScale);
      },
      [rotatedOriginalSize, cumulativeScale]
    );

    const rotateLeft = useCallback(() => {
      setCumulativeRotation((prev) => {
        const newRotation = prev - 90;
        setRotationAngle(newRotation);
        return newRotation;
      });
      const scaleX = imageSize.width / rotatedOriginalSize.width;
      const scaleY = imageSize.height / rotatedOriginalSize.height;
      console.log(
        "旋转左90度 - 图片宽度:",
        imageSize.width,
        "高度:",
        imageSize.height,
        "缩放比例X:",
        scaleX.toFixed(3),
        "缩放比例Y:",
        scaleY.toFixed(3)
      );
      handleUpdateCropRect(toolKey);
    }, [
      toolKey,
      handleUpdateCropRect,
      imageSize.width,
      imageSize.height,
      rotatedOriginalSize.width,
      rotatedOriginalSize.height,
    ]);

    const rotateRight = useCallback(() => {
      setCumulativeRotation((prev) => {
        const newRotation = prev + 90;
        setRotationAngle(newRotation);
        return newRotation;
      });
      const scaleX = imageSize.width / rotatedOriginalSize.width;
      const scaleY = imageSize.height / rotatedOriginalSize.height;
      console.log(
        "旋转右90度 - 图片宽度:",
        imageSize.width,
        "高度:",
        imageSize.height,
        "缩放比例X:",
        scaleX.toFixed(3),
        "缩放比例Y:",
        scaleY.toFixed(3)
      );
      handleUpdateCropRect(toolKey);
    }, [
      toolKey,
      handleUpdateCropRect,
      imageSize.width,
      imageSize.height,
      rotatedOriginalSize.width,
      rotatedOriginalSize.height,
    ]);

    const flipHorizontal = useCallback(() => {
      setIsFlipHorizontal((prev) => !prev);
    }, []);

    const flipVertical = useCallback(() => {
      setIsFlipVertical((prev) => !prev);
    }, []);

    const resetTransform = useCallback(() => {
      setRotationAngle(0);
      setIsFlipHorizontal(false);
      setIsFlipVertical(false);
      setCumulativeRotation(0);
    }, []);

    // 暴露给父组件的方法
    useImperativeHandle(ref, () => ({
      cropImage: () => {
        if (!skiaImage) {
          console.log("没有图片可供裁剪");
          return null;
        }
        try {
          // 计算裁剪区域相对于原始图片的坐标和尺寸
          const originalWidth = skiaImage.width();
          const originalHeight = skiaImage.height();
          const scaleX = originalWidth / imageSize.width;
          const scaleY = originalHeight / imageSize.height;

          console.log("原始图片尺寸:", originalWidth, "x", originalHeight);
          console.log("显示尺寸:", imageSize.width, "x", imageSize.height);
          console.log("缩放比例:", scaleX, scaleY);

          // 计算相对于原始图片的裁剪区域
          const sourceX = Math.max(0, cropRectShared.value.x * scaleX);
          const sourceY = Math.max(0, cropRectShared.value.y * scaleY);
          const sourceWidth = Math.max(1, cropRectShared.value.width * scaleX);
          const sourceHeight = Math.max(
            1,
            cropRectShared.value.height * scaleY
          );

          // 确保裁剪区域在图片范围内
          const boundedWidth = Math.min(sourceWidth, originalWidth - sourceX);
          const boundedHeight = Math.min(
            sourceHeight,
            originalHeight - sourceY
          );

          console.log("计算裁剪区域:", {
            sourceX,
            sourceY,
            boundedWidth,
            boundedHeight,
          });

          if (boundedWidth <= 0 || boundedHeight <= 0) {
            console.log("裁剪失败：无效的尺寸", {
              boundedWidth,
              boundedHeight,
            });
            return null;
          }

          // 限制最大尺寸以避免内存问题
          const maxSize = 2048;
          const finalWidth = Math.min(Math.floor(boundedWidth), maxSize);
          const finalHeight = Math.min(Math.floor(boundedHeight), maxSize);

          console.log("最终裁剪尺寸:", finalWidth, "x", finalHeight);

          // 创建一个新的Surface
          const surface = Skia.Surface.Make(finalWidth, finalHeight);
          if (!surface) {
            console.log("裁剪失败：Surface创建失败，尝试减小尺寸");

            // 尝试更小的尺寸
            const smallWidth = Math.min(finalWidth, 1024);
            const smallHeight = Math.min(finalHeight, 1024);
            const smallSurface = Skia.Surface.Make(smallWidth, smallHeight);

            if (!smallSurface) {
              console.log("裁剪失败：即使减小尺寸也无法创建Surface");
              return null;
            }

            const smallCanvas = smallSurface.getCanvas();
            const smallSrcRect = {
              x: Math.floor(sourceX),
              y: Math.floor(sourceY),
              width: Math.floor(boundedWidth),
              height: Math.floor(boundedHeight),
            };
            const smallDstRect = {
              x: 0,
              y: 0,
              width: smallWidth,
              height: smallHeight,
            };

            smallCanvas.drawImageRect(
              skiaImage,
              smallSrcRect,
              smallDstRect,
              Skia.Paint()
            );
            const smallCroppedImage = smallSurface.makeImageSnapshot();

            console.log(
              "裁剪成功（减小尺寸）：新图片尺寸",
              smallCroppedImage.width,
              "x",
              smallCroppedImage.height
            );
            return smallCroppedImage;
          }

          const canvas = surface.getCanvas();

          // 创建绘制区域
          const srcRect = {
            x: Math.floor(sourceX),
            y: Math.floor(sourceY),
            width: Math.floor(boundedWidth),
            height: Math.floor(boundedHeight),
          };
          const dstRect = {
            x: 0,
            y: 0,
            width: finalWidth,
            height: finalHeight,
          };

          // 绘制裁剪区域
          canvas.drawImageRect(skiaImage, srcRect, dstRect, Skia.Paint());

          // 获取裁剪后的图片
          const croppedImage = surface.makeImageSnapshot();

          console.log(
            "裁剪成功：新图片尺寸",
            croppedImage.width,
            "x",
            croppedImage.height
          );
          return croppedImage;
        } catch (error) {
          console.log("裁剪过程出错:", error);
          return null;
        }
      },
      // 获取当前裁剪框信息
      getCropRect: () => {
        return cropRectShared.value;
      },
      // 变换控制方法
      rotateImage,
      rotateLeft,
      rotateRight,
      flipHorizontal,
      flipVertical,
      resetTransform,
      // 图层管理方法
      getLayers: () => internalLayers,
      setLayers: updateLayers,
      toggleLayerVisibility,
      toggleLayerLock,
      reorderLayers,
      addLayer: (layer: Layer) => {
        const newLayers = [...internalLayers, layer];
        updateLayers(newLayers);
      },
    }));

    return (
      <View style={styles.container} onLayout={handleLayout}>
        <View
          style={[
            styles.containerContent,
            { width: imageSize.width, height: imageSize.height },
          ]}
        >
          <Canvas
            ref={canvasRef}
            style={[
              styles.canvas,
              { width: imageSize.width, height: imageSize.height },
            ]}
          >
            {/* 根据图层状态渲染图层 */}
            {internalLayers
              .filter((layer) => layer.visible)
              .sort((a, b) => a.zIndex - b.zIndex)
              .map((layer) => {
                if (layer.type === "image" && layer.id === "base-image") {
                  return (
                    <Group key={layer.id} matrix={transformMatrix}>
                      <Image
                        image={skiaImage}
                        x={0}
                        y={0}
                        width={imageSize.width}
                        height={imageSize.height}
                        fit="contain"
                      >
                        {currentFilter && (
                          <ColorMatrix matrix={currentFilter} />
                        )}
                      </Image>
                    </Group>
                  );
                }
                // 这里可以添加其他图层类型的渲染
                return null;
              })}
            {/* 遮罩层 - 裁剪框区域镂空 */}
            <Path
              path={useDerivedValue(() => {
                const currentRect = cropRectShared.value;
                if (currentRect.width <= 0) return "";

                const actualToolKey = toolKey || "rectangle";
                let cropPath = "";

                if (actualToolKey === "circle") {
                  const radius =
                    Math.min(currentRect.width, currentRect.height) / 2;
                  const centerX = currentRect.x + currentRect.width / 2;
                  const centerY = currentRect.y + currentRect.height / 2;
                  cropPath = `M ${centerX} ${centerY} m -${radius} 0 a ${radius} ${radius} 0 1 0 ${
                    radius * 2
                  } 0 a ${radius} ${radius} 0 1 0 -${radius * 2} 0`;
                } else {
                  cropPath = `M ${currentRect.x} ${currentRect.y} L ${
                    currentRect.x + currentRect.width
                  } ${currentRect.y} L ${currentRect.x + currentRect.width} ${
                    currentRect.y + currentRect.height
                  } L ${currentRect.x} ${
                    currentRect.y + currentRect.height
                  } L ${currentRect.x} ${currentRect.y} Z`;
                }

                return `
                  M 0 0
                  L ${imageSize.width} 0
                  L ${imageSize.width} ${imageSize.height}
                  L 0 ${imageSize.height}
                  Z
                  ${cropPath}
                `;
              })}
              color="rgba(0, 0, 0, 0.5)"
              style="fill"
              fillType="evenOdd"
            />

            {/* 裁剪框和拖动点显示 */}
            <Group matrix={matrix}>
              {/* 裁剪框边框 */}
              <Path
                path={getCropRectPathString}
                color="white"
                style="stroke"
                strokeWidth={2}
              />
              {/* 网格线 - 仅在拖动缩放时显示 */}
              <Path
                path={useDerivedValue(() => {
                  const currentRect = cropRectShared.value;
                  if (currentRect.width <= 0 || !isInteracting.value) return "";

                  return getGridPath({
                    x: 0,
                    y: 0,
                    width: currentRect.width,
                    height: currentRect.height,
                  });
                })}
                color="rgba(0, 122, 255, 0.3)"
                style="stroke"
                strokeWidth={0.5}
              />
              {/* 拖动点 - original模式下不显示 */}
              <Path
                path={useDerivedValue(() => {
                  if (toolKey === "original") return "";
                  const currentRect = cropRectShared.value;
                  if (currentRect.width <= 0) return "";
                  const handles = getDragHandles(
                    {
                      x: 0,
                      y: 0,
                      width: currentRect.width,
                      height: currentRect.height,
                    },
                    toolKey
                  );

                  return handles
                    .map((handle) => getHandlePath(handle))
                    .join(" ");
                })}
                color="white"
                style="fill"
              />
            </Group>
          </Canvas>
          {imageSize.width > 0 && imageSize.height > 0 && (
            <CropGestureHandler
              cropRect={cropRectShared}
              imageSize={imageSize}
              canvasPosition={canvasPosition}
              disabled={disabled}
              matrix={matrix}
              toolKey={toolKey}
              isInteracting={isInteracting}
            />
          )}
        </View>
      </View>
    );
  }
);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
  containerContent: {
    position: "relative",
  },
  canvas: {
    boxSizing: "border-box",
  },
  handle: {
    position: "absolute",
    width: 30,
    height: 30,
    backgroundColor: "transparent",
    borderRadius: 15,
  },
});

SkiaImageEditor.displayName = "SkiaImageEditor";

export { default as LayerManager } from "./LayerManager";
export default SkiaImageEditor;
